<template>
  <!--系统管理--用户管理-->
  <div class="content-area">
    <!-- 位置模块 -->
    <HeadTop></HeadTop>
    <div class="search-area">
      <div class="search-content">
        <div class="search-item"><span>用户名:</span>
          <el-input placeholder="请输入内容" v-model="searchData.username" clearable></el-input>
        </div>
        <div class="search-item">
          <span>角色类别:</span>
          <el-select v-model="searchData.role" placeholder="请选择" clearable>
            <el-option v-for="item in searchData.roleArr" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </div>
        <div class="search-item" v-if="userRole >= 3">

          <unit-data @transferSelect="transferSelect" @setStatus="setInputChange" @setInputEmpty="setInputEmpty"
                     :childName="unitDataName"></unit-data>

        </div>
      </div>
      <div class="search-footer">
        <button class="search-btn" @click="searchElevatorTesting">查询</button>
      </div>
    </div>

    <!--内容-->
    <div class="main-content">
      <div class="content-info">
        <!-- 表格数据与翻页合并模块 -->
        <DataTable :childLoad="parentLoad" :dataTableObj="dataTableObj" v-on:getPageNo="searchByPageNo" v-on:handlePageReload="pageReload"
                   v-on:getPageSize="searchByPageSize">
          <!--除查询外的操作-->
          <div slot="operate">
            <div class="some-operate">
              <button class="some-btn some-btn-add" v-if="pagePower['007002001']"
                      @click="$goRoute('/manage/systemMgr/userMgr/addUser?id=0&userId=0')">添加用户
              </button>
            </div>
          </div>
          <!-- 额外的操作以及其他因素 -->
          <div>
            <el-table-column fixed="right" align="center" label="是否启用" v-if="pagePower['007002004']" width="200">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.user.isStart"
                  @change="changeStartOrEnd(scope.row.user)"
                  active-color="#67c23a"
                  inactive-color="#ACBCC9">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" label="是否启用" v-else width="150">
              <template slot-scope="scope">
                <p>{{scope.row.user.isStart?'已启用':'未启用'}}</p>
              </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="150">
              <template slot-scope="scope">
                <div class="item-route item-special"
                     v-show="scope.row.user.isStart">
                  <div class="item-route-link" v-for="(item ,index ) in childLink" v-if="pagePower['007002002']"
                       @click="$goRoute( item.route +'?userId='+ scope.row.user.userId + '&id=' + scope.row.user.id )">
                    {{item.text}}
                  </div>
                  <div class="item-route-link" @click="showAuthorityManage(scope.row.user)"
                       v-if="pagePower['007002003']">修改权限
                  </div>
                </div>
              </template>
            </el-table-column>
          </div>
        </DataTable>
      </div>
    </div>

    <dialogPowerSet ref="dialogPower" v-on:backstageNeedPower="setPower"></dialogPowerSet>

  </div>
</template>
<style lang="scss" type="text/scss">
  @import "../../../style/entry/components/pageCommon";
</style>
<script>
  // 表格数据
  import DataTable from "../../../components/dataTable/dataTable"
  import com from "../../../js/common"
  import HeadTop from "../../../components/head-top/head-top"
  import {userPage, getUserRbac, updateUserRbac} from "@/api/getData"
  import {RoleArr} from '@/js/constant'
  import unitData from "../../../components/unitData/unitData"
  import dialogPowerSet from "../../../components/dialogPowerSet/dialogPowerSet"

  export default {
    name: 'userManage',
    components: {
      DataTable,
      HeadTop,
      unitData,
      dialogPowerSet
    },
    data() {
      return {
        unitDataName: '所属机构',
        parentLoad: '加载中...',    // 加载状态

        pagePower: JSON.parse(com.getStore('pagePowers'))['007002'] ? JSON.parse(com.getStore('pagePowers'))['007002'] : {},
        timeout: null,
        // 子页面信息
        childLink: [
          {
            route: '/manage/systemMgr/userMgr/addUser',
            text: '编辑用户'
          }
        ],

        // 搜索区域数据
        searchData: {
          username: '',
          role: '',
          roleArr: [],
          organ: '',
          organArr: [],
          departmentId: ''
        },

        // 默认的所有角色

        roleArr: RoleArr,
        // 表格组件数据
        dataTableObj: {

          // 表格数据
          tableData: [],
          // 表格标题
          tableColumns: [
            {
              text: '序号',
              width: '60',
              attributeName: 'user.index'
            },
            {
              text: '用户名',
              width: '80',
              attributeName: 'user.username'
            },
            {
              text: '创建时间',
              width: '80',
              attributeName: 'user.regTime'
            },
            {
              text: '所属角色',
              width: '80',
              attributeName: 'user.role'
            },
            {
              text: '所属机构',
              width: '140',
              attributeName: 'user.companyName'
            }
          ],

          // 翻页所需数据
          pageObj: {
            // 每页分为几条数据
            pageSize: 10,
            // 总共多少数据
            pageNum: 0,
            pageNo: 1,
            searchStatus: 2,
          },
        },

        // 查询条件
        searchMsg: {
          username: '',
          role: '',
          departmentId: ''
        },

        // 权限操作
        showDialogAuthorityTree: false,
        // 用户所能操作的权限
        userAuthorityTreeData: [],
        // 权限树名称
        defaultProps: {
          children: 'list',
          label: 'name'
        },
        // 用户已有权限
        userHasAuthority: [],
        // 权限code对应权限
        treeObj: {},
        // 当前选择用户id
        selectUserId: '',
        userRole: Number(com.getStore('role'))  // 登录用户角色
      }
    },
    created() {
      // 获取当前页面所需数据
      this.getUserManageData()
      this.checkUserRole()
    },
    methods: {

      // 根据登录用户 角色分配
      checkUserRole() {
        const role = this.userRole
        this.searchData.roleArr = this.roleArr.filter((val) => {
          return val.value < role
        })
      },

      // 获取页面所需数据
      getUserManageData() {
        let self = this;
        userPage({
          pageNo: self.dataTableObj.pageObj.pageNo,
          pageSize: self.dataTableObj.pageObj.pageSize,
          condition: self.searchMsg
        }).then(function (data) {
          // 改变aii你查询状态
          self.dataTableObj.pageObj.searchStatus = 1
          let info = data.data.data;
          let infoArr = info.data;
          if (infoArr.length > 0) {
            infoArr.forEach((i, t) => {
              i.user.index = t + 1;
              i.user.isStart = i.user.status === 1 ? true : false
              i.user.regTime = com.formatDate(i.user.regTime).substring(0, 10);
              self.roleArr.forEach((j) => {
                if (i.user.role == j.value) {
                  i.user.role = j.label;
                }
              })
            });
          } else {
            self.parentLoad = '暂无数据'    // loading(暂无数据)
          }
          self.dataTableObj.tableData = infoArr;
          self.dataTableObj.pageObj.pageNum = info.totalRecord;

        }).catch(function (data) {
          self.$message.error(data.data.message)
          self.parentLoad = data.data.message    // loading(查询失败)
          // 改变查询状态
          self.dataTableObj.pageObj.searchStatus = 0
        })
      },


      // 选择所查询机构
      transferSelect(item) {
        this.searchMsg.departmentId = item.id
      },
      // 前后信息不同时出现传递值为-1
      setInputChange() {
        this.searchMsg.departmentId = -1
      },
      // 前后信息不同时置空查询条件
      setInputEmpty() {
        this.searchMsg.departmentId = ''
      },
      // 每页多少内容
      searchByPageSize(val) {
        this.dataTableObj.pageObj.pageSize = val
        this.getUserManageData();
      },

      // 切换第几页
      searchByPageNo(val) {
        // 切换每页数目
        this.dataTableObj.pageObj.pageNo = val
        this.getUserManageData()
      },

      // 点击查询
      searchElevatorTesting: function () {
        // 跳出查询等待框
        this.searchMsg.role = this.searchData.role
        this.searchMsg.username = this.searchData.username
        this.getUserManageData()
      },

      // 显示权限树判断
      showAuthorityManage(val) {
        // 此时获取用户权限
        let param = {}
        param.userId = val.userId
        this.selectUserId = val.userId
        getUserRbac(param).then((res) => {
          const authorityArr = res.data.data
          this.$refs.dialogPower.getEleNeedPower(authorityArr)
        }).catch(err => this.$message.error(err.data.message))
      },
      // 最后设置权限
      setPower(backNeedPower) {
        // 修改用户权限
        let params = {}
        params.auths = backNeedPower
        params.user = {}
        params.user.userId = this.selectUserId
        updateUserRbac(params).then((res) => {
          com.mask()
          this.$message.success({
            message: '修改成功',
            duration: 1500,
            onClose: () => {
              com.unmask()
              this.$refs.dialogPower.hideDialog()
            }
          })
        }).catch(err => {
          this.$message.error(err.data.message)
          this.$refs.dialogPower.hideDialog()
        })
      },
      // 用户是否启用
      changeStartOrEnd(val) {
        const bol = val.isStart
        const userId = val.userId
        let url, sucMsg, errMsg
        if (bol) {
          url = `${com.basePath}/usercenter-web/user/enable`
          sucMsg = '启用成功'
          errMsg = '启用失败'
        } else {
          url = `${com.basePath}/usercenter-web/user/disable`
          sucMsg = '禁用成功'
          errMsg = '禁用失败'
        }
        com.axio.post(url, {
          userId: userId
        }).then(val => this.$message.success(sucMsg)).catch((err) => {
          val.isStart = !val.isStart
          this.$message.error(err.data.message ? err.data.message : errMsg)
        })
      },

      // 页面刷新
      pageReload(){
        this.getUserManageData();
      }
    }
  }
</script>
